//
//  HTNavigationController.m
//  HTHeartPaste
//
//  Created by 开发者 on 16/3/9.
//  Copyright © 2016年 meidaer. All rights reserved.
//

#import "HTNavigationController.h"
#import "UIBarButtonItem+Extension.h"
#import "POPAnimation.h"
#import "HTBackTextViewController.h"
#import "HTBackTextIsTitleViewController.h"
#import "UIView+HTExtension.h"
#import "CXSnapImageView.h"

#define kAlpha 0.9f
#define ANIMATIONDURATION 0.3f
#define BACKDURATION 0.1f
#define kTag 888
#define kWindow [[UIApplication sharedApplication] keyWindow]
#define MAXMOVE 100

#define kScreenBounds ([[UIScreen mainScreen] bounds])
#define kScreenWidth (kScreenBounds.size.width)
#define kScreenHeight (kScreenBounds.size.height)

#define RGBColor(r, g, b)  [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:1]

@interface HTNavigationController () <UIGestureRecognizerDelegate>
{
    NSMutableArray *_screenShots; //截屏图片数组
    UIImageView *_prevPageView;
    CXSnapImageView *_snapImageViewModel;
    BOOL _isAddNavigationBar; // 侧滑分两钟，是否添加bar
    BOOL _animatedFlag;  // 是否正在进行切换的动画
}

@end

@implementation HTNavigationController

+ (void)initialize
{
    // 设置整个项目所有item的主题样式
   
    NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
    textAttrs[NSForegroundColorAttributeName] = [UIColor whiteColor];
    textAttrs[NSFontAttributeName] = [UIFont boldSystemFontOfSize:19];
    UINavigationBar *navigationBar = [UINavigationBar appearance];
    [navigationBar setTitleTextAttributes:textAttrs]; // 设置标题的文字样式
    navigationBar.barTintColor = RGBColor(40, 41, 46);   //  设置整个导航栏的背景颜色
    navigationBar.tintColor = [UIColor whiteColor]; // 设置整个主题的样式
    

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // 设置普通状态
    // key：NS****AttributeName

    _screenShots = [NSMutableArray array];
    UIPanGestureRecognizer *panGestureRecognizer =
    [[UIPanGestureRecognizer alloc]initWithTarget:self
                                           action:@selector(handlePanGesture:)];
    panGestureRecognizer.delegate = self;
    self.interactivePopGestureRecognizer.enabled = NO;
    [self.view addGestureRecognizer:panGestureRecognizer];

}

- (void)handlePanGesture:(UIPanGestureRecognizer *)panGestureRecognizer{
    UIGestureRecognizerState state = panGestureRecognizer.state;
    CGPoint translationPoint = [panGestureRecognizer translationInView:self.view];
    switch (state) {
        case UIGestureRecognizerStateBegan:
        {
            UIImageView *backImageView = _snapImageViewModel.imageView;
            backImageView.alpha = kAlpha;
            [kWindow insertSubview:backImageView
                           atIndex:0];
            backImageView.x = -kScreenBounds.size.width / 2;
            if (_isAddNavigationBar) {
                [self.navigationBar addSubview:_snapImageViewModel.navigatioBar];
                _snapImageViewModel.navigatioBar.alpha = 0;
            }
            
            break;
        }
        case UIGestureRecognizerStateChanged:
        {
            if (translationPoint.x < 0) {
                translationPoint.x = 0;
            }
            
            if (translationPoint.x > kScreenWidth) {
                translationPoint.x = kScreenWidth;
            }
            float alpha = MIN(1.0, kAlpha + translationPoint.x / kScreenWidth * (1 - kAlpha));
            _snapImageViewModel.imageView.alpha = alpha;
            // 设置偏移量
            [_snapImageViewModel.imageView setTransform:CGAffineTransformMakeTranslation(translationPoint.x / 2, 0)];
            
            if (_isAddNavigationBar) {
                CGFloat k = translationPoint.x / kScreenWidth;
                [self barTransitionWithAlpha:1 - k];
                _snapImageViewModel.navigatioBar.alpha = k;
                self.visibleViewController.view.transform = CGAffineTransformMakeTranslation(translationPoint.x, 0);
            }  else {
                self.view.transform = CGAffineTransformMakeTranslation(translationPoint.x, 0);
            }
            
            break;
        }
        case UIGestureRecognizerStateCancelled:
        case UIGestureRecognizerStateEnded:
        {
            CGPoint velocity = [panGestureRecognizer velocityInView:self.view];
            BOOL pop = velocity.x >= 0 && translationPoint.x > MAXMOVE;
            [self handlePopResult:pop];
            break;
        }
        default:
            break;
    }
}

#pragma mark - Override NavigationConrroller Methods

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
    // 保存屏幕截图，navigaitonbar, 序号和 navigationbar是否隐藏
    // 延时处理，好让按钮等恢复状态
    if (self.viewControllers.count > 0) {
        UIViewController *previousViewController = [self.viewControllers lastObject];

        NSTimeInterval time = CFAbsoluteTimeGetCurrent();

        CXSnapImageView *snap = [[CXSnapImageView alloc] init];
        snap.isNavigationBarHidden = self.navigationBarHidden;
        if (!self.navigationBarHidden) {
            snap.navigatioBar =[[UIImageView alloc]initWithImage:[self.navigationBar snapshot]];
        }
        snap.order = self.viewControllers.count;

        double delayInSeconds = animated ? 0.35 : 0.1; // 等按钮状态恢复到normal状态
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
        UIWindow *window = kWindow;
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            UIImageView *shotImageView = [[UIImageView alloc]initWithImage:[window snapshot]];
            snap.imageView = shotImageView;
            [_screenShots addObject:snap];
        });
        [self startAnimated:animated];
        
        NSTimeInterval sectime = CFAbsoluteTimeGetCurrent();

        NSLog(@"time = %f",sectime - time);
        viewController.hidesBottomBarWhenPushed = YES;
        //        viewController.navigationController.navigationBar.hidden = NO;
        /* 设置导航栏上面的内容 */
        // 设置左边的返回按钮
        if ([viewController isKindOfClass:[HTBackTextViewController class]]) {
            UIBarButtonItem *backItem = [UIBarButtonItem itemWithTarget:self action:@selector(back) image:@"ht_orginal_back" title:@"返回"];
            
            UIBarButtonItem *fixedButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
            
            fixedButton.width = -8;
            
            viewController.navigationItem.leftBarButtonItems = @[fixedButton, backItem];
            
        }  else if ([viewController isKindOfClass:[HTBackTextIsTitleViewController class]]) {
            HTBackTextIsTitleViewController *titlViewVc = (HTBackTextIsTitleViewController *)viewController;
            UIBarButtonItem *backItem = [UIBarButtonItem itemWithTarget:self action:@selector(back) image:@"ht_orginal_back" title:titlViewVc.backStr];
            
            UIBarButtonItem *fixedButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
            
            fixedButton.width = -8;
            
            viewController.navigationItem.leftBarButtonItems = @[fixedButton, backItem];
            
        } else {
            UIViewController *viewControllerOne = self.viewControllers[self.viewControllers.count - 1];
            NSString *title = viewControllerOne.navigationItem.title;
            UIBarButtonItem *backItem = [UIBarButtonItem itemWithTarget:self action:@selector(back) image:@"ht_orginal_back" title:title];
            
            UIBarButtonItem *fixedButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
            
            fixedButton.width = -8;
            
            viewController.navigationItem.leftBarButtonItems = @[fixedButton, backItem];
            
        }
        NSTimeInterval threeTime = CFAbsoluteTimeGetCurrent();
        
        NSLog(@"totalTime = %f",(threeTime - time));
    }
    [super pushViewController:viewController
                     animated:animated];
}

- (void)setViewControllers:(NSArray<__kindof UIViewController *> *)viewControllers
{
    // 这里根据实际情况来;这里一般是去掉某个中间的控制器
    if (viewControllers.count != self.viewControllers.count + 1  && viewControllers.count > 2) {
        
        for (int i = 0; i < self.viewControllers.count; i++) {
            UIViewController *viewController = self.viewControllers[i];
            if (viewController == viewControllers[viewControllers.count - 2]) {
                [_screenShots removeObjectsInRange:NSMakeRange(i, _screenShots.count - i)];
                break;
            }
        }
    }
    [super setViewControllers:viewControllers];
}

- (UIViewController *)popViewControllerAnimated:(BOOL)animated
{
    [_screenShots removeLastObject];
    [self startAnimated:animated];
    
    return  [super popViewControllerAnimated:animated];
}

- (NSArray<UIViewController *> *)popToRootViewControllerAnimated:(BOOL)animated
{
    [_screenShots removeAllObjects];
    [self startAnimated:animated];
    
    return  [super popToRootViewControllerAnimated:animated];
}

- (NSArray<UIViewController *> *)popToViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    NSInteger index = [self.viewControllers indexOfObject:viewController];
    NSInteger count = _screenShots.count;
    [_screenShots removeObjectsInRange:NSMakeRange(index,count -  index)];
    return [super popToViewController:viewController animated:animated];
}



#pragma mark - GestureRecognizer Delegate

- (BOOL)gestureRecognizerShouldBegin:(UIPanGestureRecognizer *)gestureRecognizer
{
    if (self.viewControllers.count < 2) return NO;
    if (_animatedFlag) return NO;  // 避免在动画中滑动
    CGPoint touchPoint = [gestureRecognizer locationInView:self.view];
    if (touchPoint.y < 64) return NO;
    
    CGPoint translation = [gestureRecognizer translationInView:self.view];
    // 是否是左滑或者上下滑
    if (translation.x <= 0 || fabs(translation.y / translation.x) > 0.75) return NO;
    
    _snapImageViewModel = _screenShots.lastObject;
    if (_snapImageViewModel.disablePanback) return NO;
    
    if (self.isNavigationBarHidden || _snapImageViewModel.isNavigationBarHidden) {
        _isAddNavigationBar = NO;
    } else {
        _isAddNavigationBar = YES;
    }
    return YES;
}

#pragma mark - Set Methods

- (void)setDisablePanBack:(BOOL)disablePanBack
{
    _disablePanBack = disablePanBack;
    CXSnapImageView *model = _screenShots.lastObject;
    model.disablePanback = _disablePanBack;
}

- (void)setEnableNavigationBarTransform:(BOOL)enableNavigationBarTransform
{
    _enableNavigationBarTransform = enableNavigationBarTransform;
    CXSnapImageView *model = _screenShots.lastObject;
    model.isNavigationBarHidden = YES;
}



#pragma mark - Help Methods

- (void)handlePopResult:(BOOL)isPop {
    [[UIApplication sharedApplication] beginIgnoringInteractionEvents];
    CGFloat alpha = isPop ? 1.0 : 0;
    [UIView animateWithDuration:0.3 animations:^{
        if (isPop) {
            _snapImageViewModel.imageView.alpha = alpha;
            _snapImageViewModel.imageView.transform = CGAffineTransformMakeTranslation(kScreenWidth / 2, 0);
            if (_isAddNavigationBar) {
                _snapImageViewModel.navigatioBar.alpha = alpha;
                self.visibleViewController.view.transform = CGAffineTransformMakeTranslation(kScreenWidth, 0);
            } else {
                self.view.transform = CGAffineTransformMakeTranslation(kScreenWidth, 0);
            }
        } else {
            _snapImageViewModel.imageView.alpha = kAlpha;
            _snapImageViewModel.imageView.transform = CGAffineTransformIdentity;
            if (_isAddNavigationBar) {
                _snapImageViewModel.navigatioBar.alpha = alpha;
                self.visibleViewController.view.transform = CGAffineTransformIdentity;
            } else {
                self.view.transform = CGAffineTransformIdentity;
            }
        }
        
    } completion:^(BOOL finished) {
        [[UIApplication sharedApplication] endIgnoringInteractionEvents];
        
        [_snapImageViewModel.imageView removeFromSuperview];
        if (_isAddNavigationBar) {
            self.visibleViewController.view.transform = CGAffineTransformIdentity;
            [_snapImageViewModel.navigatioBar removeFromSuperview];
            [self barTransitionWithAlpha:1.0];
        } else {
            self.view.transform = CGAffineTransformIdentity;
        }
        if (isPop) {
            [self popViewControllerAnimated:NO];
        }
    }];
}

// 改变navigationbar上子控件的alpha
- (void)barTransitionWithAlpha:(CGFloat)alpha
{
    // 除了Background,其它一律改变的他们的alpha
    for (UIView *view in self.navigationBar.subviews) {
        if (!CGRectEqualToRect(view.frame, CGRectMake(0, -20, kScreenWidth, 64))) {
            view.alpha = alpha;
        }
    }
}


- (void)startAnimated:(BOOL)animated
{
    _animatedFlag = YES;
    
    NSTimeInterval delay = animated ? 0.8 : 0.1;
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(finishedAnimated) object:nil];
    [self performSelector:@selector(finishedAnimated) withObject:nil afterDelay:delay];
}

- (void)finishedAnimated
{
    _animatedFlag = NO;
}


- (void)back
{
#warning 这里要用self，不是self.navigationController
    // 因为self本来就是一个导航控制器，self.navigationController这里是nil的

    if (self.viewControllers.count == 1) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }else {
        [self popViewControllerAnimated:YES];
    }
}






@end
